<?php
namespace app\first\controller;
use aiplat\SDK\API;
use aiplat\SDK\Configer;
use Curl\Curl;
use think\facade\Cache;
use think\facade\Config;
use think\Image;
use think\response\Download;

/**
 * Class OCR
 * @title 图片识别
 * @url /v1/ocr
 * @desc  有关于图片识别
 * @route('v1/ocr')
 * @version 1.0
 * @package app\first\controller
 */
class Ocr extends Base{
    //是否开启授权认证
    public $apiAuth = false;
    //附加方法
    protected $extraActionList = ['id_cards'];
    protected $client = null;
    protected $token = null;

    /**
     * Ocr constructor.
     * @throws \Expnull\Ocr\Exceptions\HttpException
     */
    public function __construct(){
        parent::__construct();
        $this->client = new \Expnull\Ocr\Ocr(Config::get('baidu_ocr.apiKey'),Config::get('baidu_ocr.secretKey'));
        $name = Config::get('baidu_ocr.apiKey').'_token';
        if(!Cache::has($name)){
           $token = $this->client->getToken();
           Cache::set($name,$token,60 * 60 * 24 * 29);
           $this->token = $token;
        }else{
            $this->token = Cache::get($name);
        }
        $this->client->setProbability('true');
        $this->client->setDetectLanguage('true');
    }

    /**
     * @title 身份证识别(百度)
     * @method id_cards
     * @param string $file 文件 true  图片地址/Base64格式
     * @param int $type 类型 true 1 1正面,2反面
     * @route('v1/ocr/id_cards','post')
     * @return \think\facade\Response|\think\response\Json|\think\response\Jsonp|\think\response\Redirect|\think\response\View|\think\response\Xml
     * @throws \Expnull\Ocr\Exceptions\HttpException
     */
    public function id_cards($file='',$type = 1){
        if(empty($file)){
            return $this->sendError(0,'缺少参数');
        }
        if(strpos($file,'http://')!==false){
            $this->client->setImageUrl($file);
        }else{
            $this->client->setImage($file);
        }
        $words = $this->client->getImgWords($this->token['access_token']);
        $_data = [];
        if($type==1){
            foreach ($words['words_result'] as $k => $v){
                if(strpos($v['words'],'名')!==false){
                    $tmp = explode('名',$v['words']);
                    $_data['name'] = end($tmp);
                }elseif(strpos($v['words'],'性别')!==false){
                    $tmp = explode('性别',$v['words']);
                    $tmp1 = explode('民族',end($tmp));
                    $_data['sex'] = $tmp1[0];
                    $_data['minzu'] = $tmp1[1];
                }elseif(strpos($v['words'],'身份号码')!==false){
                    $tmp = explode('身份号码',$v['words']);
                    $_data['no'] = end($tmp);
                }elseif(strpos($v['words'],'出生')!==false){
                    $tmp = explode('出生',$v['words']);
                    $_data['birthday'] = end($tmp);
                }else{
                    $_data['address'][] = ' '.$v['words'];
                }
            }
            $_data['address'] = str_replace('住址','',
                str_replace(' ','',
                    implode(' ',$_data['address'])));
        }else{
            foreach ($words['words_result'] as $k => $v){
                if(strpos($v['words'],'签发机关')!==false){
                    $tmp = explode('签发机关',$v['words']);
                    $_data['authority'] = end($tmp);
                }elseif(strpos($v['words'],'有效期限')!==false){
                    $tmp = explode('有效期限',$v['words']);
                    $_data['expiry_date'] = end($tmp);
                }else{
                    $_data['sign'][] = ' '.$v['words'];
                }
            }
            $_data['sign'] = str_replace('た。','',
                str_replace(' ','',
                    implode(' ',$_data['sign'])));
        }
        return $this->sendSuccess($_data);
    }

    /**
     * @title 身份证识别 （腾讯）
     * @method tx_idcard
     * @param string $image 身份证 true  原始图片的base64编码数据（原图大小上限1MB，支持JPG、PNG、BMP格式）
     * @param int $type 身份证图片类型 true 1 1-正面,2-反面
     * @route('v1/ocr/tx_idcard','post')
     * @return \think\facade\Response|\think\response\Json|\think\response\Jsonp|\think\response\Redirect|\think\response\Xml
     * @throws \ErrorException
     */
    public function tx_idcard($image='',$type=1){
        if(strpos($image,'http://')!==false){
            $name = explode('.',$image);
            $_name = end($name);
            $path = "./tmp.{$_name}";
            $curl = new Curl();
            $curl->get($image);
            $curl->close();
            file_put_contents($path,$curl->response);
            if(strlen($curl->response) / 1024 / 1024){
                $_image = Image::open($path);
                $_image->thumb($_image->width() / 2,
                    $_image->height() / 2,
                    \think\Image::THUMB_SOUTHEAST)
                    ->save($path,null,50);
                $image = base64_encode(file_get_contents($path));
                unlink($path);
            }
        }
        $config = Config::get('aiplat.');
        Configer::setAppInfo($config['app_id'],$config['app_key']);
        $params = [
            'card_type'=>$type==1?0:1,
            'image'=> $image
        ];
        $response = API::ocr_idcardocr($params);
        if($response['ret']==0){
            $data = $response['data'];
            unset($data['frontimage']);
            unset($data['authority']);
            unset($data['valid_date']);
            unset($data['backimage']);
        }else{
            $data = $response;
        }
        return $this->sendSuccess($data);
    }
}